import React, { useEffect, useState } from 'react'
import { Switch, Table, Button, Modal } from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { connect, useNavigate } from 'umi';
import type { ColumnsType } from 'antd/es/table';
import _ from 'lodash';
import AddUserModal from '@/components/AddUserModal';
import UpdateUserModal from '@/components/UpdateUserModal';

interface DataType {
    id: number;
    region: string;
    username: string;
    role: any;
    roleState: number
}
type stringKey=Record<string,string>;
function UserManageList(props: any) {
    const { dispatch, usersList,roleList,regionList,currentUserList } = props;
    //记录表格DataSource的数据
    const [usersData,setUsersData]=useState(usersList);
    // 控制对话弹出框是否显示的状态
    const [deleteOpen, setDeleteOpen] = useState(false);
    //对话弹出框确认框异步操作时的加载
    const [deleteConfirmLoading, setDeleteConfirmLoading] = useState(false);
    // 新增用户的对话框是否显示
    const [addOpen, setAddOpen] = useState(false);
    // 更新用户的对话框是否显示
    const [updateOpen, setUpdateOpen] = useState(false);
    // 表格的loading
    const [tableLoading, setTableLoading] = useState(false);
    // 记录当前选中的item
    const [currentItem, setCurrentItem] = useState(null);
    // 记录用于用户名筛选数据
    const [filterUsernameData, setFilterUsernameData] = useState([]);
    // 记录用于用户名筛选数据
    const [filterRegionData, setFilterRegionData] = useState([]);
    // 记录用于用户名筛选数据
    const [filterRoleNameData, setFilterRoleNameData] = useState([]);
    //这个状态传给子组件，该状态不断变化（每点一次更新按钮），从而使点击同一个item也会重新渲染
    const[isRenderState,setIsRenderState]=useState(false);
    // 记录当前用户的信息
    const [currentUserData,setCurrentUserData]=useState(null)
    // 路由跳转方法
    const navigate=useNavigate()
    useEffect(()=>{
        if(currentUserList.length<=0){
            if(localStorage.getItem('token')){
                setCurrentUserData(JSON.parse((localStorage.getItem('token')as string))[0])
            }
            else{
                navigate('/login')
            }
        }
        else{
            setCurrentUserData(currentUserList[0])
        }
    },[currentUserList])
    useEffect(() => {
        if (usersList?.length === 0) {
            setTableLoading(true);
            dispatch({
                type: 'StandBox/getUsersList',
                payload: {
                    setTableLoading
                }
            })
        }
        else if (roleList?.length === 0) {
            setTableLoading(true);
            dispatch({
                type: 'StandBox/getRoleList',
                payload: {
                    setTableLoading
                }
            })
        }
        else if (regionList?.length === 0) {
            setTableLoading(true);
            dispatch({
                type: 'StandBox/getRegionList',
                payload: {
                    setTableLoading
                }
            })
        }
        else {
            const filterUsersData = usersList.map((item: { username: string }) => {
                return {
                    text: item.username,
                    value: item.username
                }
            });
            const filterRegionData = regionList.map((item: { title: string }) => {
                return {
                    text: item.title,
                    value: item.title
                }
            });
            (filterRegionData as Array<any>).unshift({text:'全球',value:'全球'});
            const filterRoleNameData = roleList.map((item: { roleName: string }) => {
                return {
                    text: item.roleName,
                    value: item.roleName
                }
            });
            let newUsersData : Array<any>=_.cloneDeep(usersList).reverse();
            const roleObj:stringKey={
                '1':'SuperAdmin',
                '2':'Admin',
                '3':'Editor'
            }
            newUsersData=_.cloneDeep(newUsersData).filter(item=>{
                if(roleObj[(currentUserData as any)?.roleId]==='SuperAdmin'){
                    return true
                }
                else if(roleObj[(currentUserData as any)?.roleId]==='Admin'){
                    return item.id===(currentUserData as any)?.id||(item.region===(currentUserData as any)?.region&&roleObj[(item as any)?.roleId]==='Editor')
                }
                else if(roleObj[(currentUserData as any)?.roleId]==='Editor'){
                    return item.id===(currentUserData as any)?.id
                }
                else{
                    return item.id===(currentUserData as any)?.id
                }
            })
            setUsersData(newUsersData);
            setFilterUsernameData(filterUsersData);
            setFilterRegionData(filterRegionData);
            setFilterRoleNameData(filterRoleNameData);
        }
    }, [usersList,currentUserData,regionList,roleList]);


    // 开关组件的点击事件,修改用户列表的用户状态
    const handelModifyState = (item: any) => {
        setTableLoading(true);
        const newItem = _.cloneDeep(item);
        newItem.roleState = !item.roleState;
        dispatch({
            type: 'StandBox/modifyUsersList',
            payload: {
                setLoading: setTableLoading,
                usersItem: newItem,
                users: usersList
            }
        })
    }
    //气泡确认框确认删除的点击事件
    const handleDelOk = (item: any) => {
        setDeleteConfirmLoading(true);
        setTableLoading(true);
        dispatch({
            type: 'StandBox/deleteUsersList',
            payload: {
                setLoading: setTableLoading,
                setDelConfirmLoading: setDeleteConfirmLoading,
                setDeleteOpen,
                usersItem: item,
                users: usersList
            }
        })
    };
    //删除确认框取消的点击事件
    const handleCancel = () => {
        setDeleteOpen(false);
    }

    const columns: ColumnsType<DataType> = [
        {
            title: '区域',    //标题
            dataIndex: 'region',     //匹配的字段名 
            key: 'region',
            render: (region: string) => {
                return <b>{region === '' ? '全球' : region}</b>
            },
            filters: filterRegionData,
            filterSearch: true,
            onFilter: (value: any, record) => value==='全球'?record.region==='':record.region.startsWith(value),
        },
        {
            title: '用户名',    //标题
            dataIndex: 'username',     //匹配的字段名 
            key: 'username',
            filters: filterUsernameData,
            filterSearch: true,
            onFilter: (value: any, record) => record.username.startsWith(value),
        },
        {
            title: '角色名称',    //标题
            dataIndex: 'role',     //匹配的字段名 
            key: 'role',
            render: (role: any) => {
                return role?.roleName
            },
            filters: filterRoleNameData,
            filterSearch: true,
            onFilter: (value: any, record) => record.role.roleName.startsWith(value),
        },
        {
            title: '用户状态',    //标题
            dataIndex: 'roleState',     //匹配的字段名 
            key: 'roleState',
            render: (roleState: any, item: any) => {
                return <Switch checked={roleState} onClick={() => { handelModifyState(item) }} disabled={item.default}></Switch>
            }
        },
        {
            title: '操作',
            render: (item: any) => {
                return (<div>
                    <Button disabled={item.default} danger shape="circle" style={{ 'marginRight': '10px' }} icon={<DeleteOutlined />} onClick={() => {
                        setCurrentItem(item);
                        setDeleteOpen(true);
                    }}>
                    </Button>
                    <Button disabled={item.default} type="primary" shape="circle" icon={<EditOutlined />} onClick={() => {
                        setCurrentItem(item);
                        setUpdateOpen(true);
                        setIsRenderState(!isRenderState);
                    }}></Button>
                </div>)
            }
        }
    ]
    return (
        <div>
            <Button type="primary" onClick={() => { setAddOpen(true) }}>添加角色</Button>
            {/* 删除的对话框 */}
            <Modal
                title={`【${(currentItem as any)?.username}】删除`}
                open={deleteOpen}
                onOk={() => { handleDelOk(currentItem) }}
                confirmLoading={deleteConfirmLoading}
                onCancel={handleCancel}
                okText='确定'
                cancelText='取消'
            >
                <p>是否要删除该用户信息？</p>
            </Modal>
            <AddUserModal addOpen={addOpen} setAddOpen={setAddOpen} setTableLoading={setTableLoading}></AddUserModal>
            <UpdateUserModal updateOpen={updateOpen} setUpdateOpen={setUpdateOpen} 
            setTableLoading={setTableLoading} currentItem={currentItem} isRenderState={isRenderState}></UpdateUserModal>
            <Table dataSource={usersData} columns={columns} loading={tableLoading}
                rowKey={item => item.id} sticky pagination={{
                    pageSize: 5
                }} />
        </div>
    )
}

const mapStateToProps = (state: any) => {
    return {
        usersList: state.StandBox.usersList,
        roleList:state.StandBox.roleList,
        regionList:state.StandBox.regionList,
        currentUserList:state.StandBox.currentUserList,
    }
}
export default connect(mapStateToProps)(UserManageList)